//
//  SAMapView.m
//  SuperApp
//
//  Created by VanJay on 2020/4/23.
//  Copyright © 2020 chaos network technology. All rights reserved.
//

#import "SAMapView.h"
#import "SAAnnotation.h"
#import "SAAnnotationView.h"
#import <MapKit/MapKit.h>

@interface SAMapView () <MKMapViewDelegate>

@end

@implementation SAMapView

- (void)hd_setupViews {
    [self addSubview:self.mapView];
}

- (void)updateConstraints {

    [self.mapView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];

    [super updateConstraints];
}

#pragma mark - WKMapViewDelegate
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:SAAnnotation.class]) {
        SAAnnotationView *view = (SAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:NSStringFromClass(SAAnnotationView.class)];
        if (!view) {
            view = [[SAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:NSStringFromClass(SAAnnotationView.class)];
        }
        view.annotation = annotation;
        return view;
    }
    return nil;
}

/// 加个动画
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views {
    for (MKAnnotationView *annotationView in views) {
        CGRect targetRect = annotationView.frame;
        annotationView.frame = CGRectMake(targetRect.origin.x, 0, targetRect.size.width, targetRect.size.height);
        [UIView animateWithDuration:0.3
                         animations:^{
                             annotationView.frame = targetRect;
                         }];
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:didUpdateUserLocation:)]) {
        [self.delegate mapView:self didUpdateUserLocation:userLocation];
    }
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapView:regionDidChangeAnimated:)]) {
        [self.delegate mapView:self regionDidChangeAnimated:animated];
    }
}

#pragma mark - lazy load
- (MKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MKMapView alloc] init];
        _mapView.delegate = self;
    }
    return _mapView;
}

@end
